<template>
    <div class="context-menu" :style="{ top: contextMenuTop + 'px', left: contextMenuLeft + 'px' }" v-if="visible">
        <div @click="top">
            <el-icon><Upload /></el-icon>
            <span>置顶</span>
        </div>
        <div @click="up">
            <el-icon><Top /></el-icon>
            <span>上移</span>
        </div>
        <div @click="down">
            <el-icon><Bottom /></el-icon>
            <span>下移</span>
        </div>
        <div @click="bottom">
            <el-icon><Download /></el-icon>
            <span>置底</span>
        </div>
        <div class="spliter"></div>
        <div @click="removeCmp">
            <el-icon><delete /></el-icon>
            <span>删除</span>
        </div>
    </div>
</template>
<script setup>
import { onMounted } from "vue";
import * as _ from "lodash";

const model = defineModel();
const contextMenuTop = ref(0);
const contextMenuLeft = ref(0);
const visible = ref(false);
let currentCmp;
const emits = defineEmits(["change"]);

onMounted(() => {
    document.addEventListener("click", () => {
        visible.value = false;
    });
});

function show(e, cmp) {
    currentCmp = cmp;
    contextMenuLeft.value = e.clientX;
    contextMenuTop.value = e.clientY;
    visible.value = true;
}

function removeCmp() {
    let children = model.value.children;
    let idx = children.indexOf(currentCmp);
    children.splice(idx, 1);
    currentCmp = null;
    visible.value = false;
    emits("change");
}

function setLevel(callback) {
    let children = model.value.children;
    let idx = children.indexOf(currentCmp);
    children.splice(idx, 1);
    callback(children, idx);
    currentCmp = null;
    visible.value = false;
    emits("change");
}

function top() {
    // 当前组件置顶
    setLevel((children) => children.splice(children.length, 0, currentCmp));
}

function up() {
    setLevel((children, idx) => children.splice(idx + 1, 0, currentCmp));
}

function bottom() {
    setLevel((children) => children.splice(0, 0, currentCmp));
}

function down() {
    setLevel((children, idx) => children.splice(idx - 1, 0, currentCmp));
}

function hide() {
    visible.value = false;
}

function copy() {
    let cmp = _.cloneDeep(currentCmp);
    cmp.id = app.uuid();
    model.value.children.push(cmp);
    emits("change");
}

defineExpose({ show, hide });
</script>

<style lang="scss" scoped>
.context-menu {
    --bg_color: #fff;
    --text_color: #222;
    --border_color: #eee;

    background: var(--bg_color);
    color: var(--text_color);
    position: fixed;
    box-shadow: 0 0 4px #ddd;
    z-index: 10;

    > div:not(.spliter) {
        padding: 6px 30px;
        cursor: pointer;
        display: flex;
        align-items: center;
        flex-direction: row;
        &:hover {
            background: var(--primary_color);
            color: #eee;
        }
    }

    .spliter {
        height: 1px;
        width: 100%;
        background: var(--border_color);
        margin: 8px 0;
    }
}
</style>
